<template>
  <div style="padding: 5px;">
    <!-- 搜索区域 -->
    <div style="margin: 10px 0;">
      <el-input v-model="params.title" placeholder="请输入会员名称" style="width: 20%;" @keyup.enter="load"></el-input>
      <el-button style="margin-left: 5px" type="warning" @click="reset"><i class="el-icon-refresh"></i>重置</el-button>
    </div>
    <!-- 用户信息表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="loginId" label="登录ID" style="width: 100px;" />
      <el-table-column prop="username" label="账户名" />
      <el-table-column prop="password" label="密码" />
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button @click="showEditDialog(scope.row)">修改</el-button>
          <el-button @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div style="margin: 5px 0;">
      <el-pagination
          v-model:current-page="params.pageNum"
          v-model:page-size="params.pageSize"
          :disabled="disabled"
          :background="background"
          layout="prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑用户对话框 -->
    <el-dialog title="编辑用户" v-model="dialogFormVisible">
      <el-form :model="editUser" ref="editUserForm" label-width="120px">
        <el-form-item label="登录ID" prop="loginId">
          <el-input v-model="editUser.loginId" disabled></el-input>
        </el-form-item>
        <el-form-item label="账户名" prop="username">
          <el-input v-model="editUser.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editUser.password" type="password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitEditForm('editUserForm')">提交</el-button>
          <el-button @click="editDialogVisiblet()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import request from "../../utils/request";
import { reactive, ref } from 'vue';
export default {
  name: 'UserView',
  data() {
    return {
      total: 0,
      tableData: [],
      params: {
        title: '',
        pageSize: 10,
        pageNum: 1
      },
      dialogFormVisible: ref(false),
      editUser: {
        loginId: '',
        username: '',
        password: ''
      }
    };
  },
  created() {
    this.load();
  },
  methods: {
    load() {
      request.get('/user/page', {
        params: this.params
      }).then(res => {
        if (res.code === '200') {
          this.tableData = res.data.list;
          this.total = res.data.total;
        }
      });
    },
    showEditDialog(row) {
      this.editUser = { ...row };
      this.dialogFormVisible = ref(true)
    },
    editDialogVisiblet(){
      this.dialogFormVisible = ref(false)
    },
    submitEditForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          request.put(`/user/${this.editUser.loginId}`, this.editUser)
              .then(res => {
                if (res.code === '200') {
                  this.$message.success('用户信息更新成功');
                  this.dialogFormVisible = ref(false)
                  this.load(); // 重新加载表格数据
                } else {
                  this.$message.error('用户信息更新失败');
                  this.dialogFormVisible = ref(false)
                }
              })
              .catch(error => {
                console.error('Error updating user:', error);
                this.$message.error('用户信息更新失败');
              });
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.delete(`/user/${row.loginId}`)
            .then(res => {
              if (res.code === '200') {
                this.$message.success('用户删除成功');
                this.load(); // 重新加载表格数据
              } else {
                this.$message.error('用户删除失败');
              }
            })
            .catch(error => {
              console.error('Error deleting user:', error);
              this.$message.error('用户删除失败');
            });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    handleSizeChange(size) {
      this.params.pageSize = size;
      this.load();
    },
    handleCurrentChange(pageNum) {
      console.log(pageNum); // test 打印
      this.params.pageNum = pageNum;
      this.load();
    },
    reset() {
      this.params = {
        title: '',
        pageSize: 10,
        pageNum: 1
      };
      this.load();
    }
  }
};
</script>